package com.dx.oa.sysmng.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.commons.codec.DecoderException;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.druid.util.StringUtils;
import com.dx.oa.framework.util.UserUtils;
import com.dx.oa.sysmng.entity.Menu;
import com.dx.oa.sysmng.entity.User;
import com.dx.oa.sysmng.service.IMenuService;
import com.dx.oa.sysmng.service.IUserService;

@Controller
public class LoginController {
	
	@Autowired
	private IUserService userService;
	
	@Autowired
	private IMenuService menuService;
//	public IUserService getUserService() {
//		return userService;
//	}
//
//	public void setUserService(IUserService userService) {
//		this.userService = userService;
//	}

	private static Logger logger = Logger.getLogger(LoginController.class);

	@RequestMapping("/gotoLogin")
	public String gotoLogin()
	{
		return "login";
	}
	
	@RequestMapping("/login")
	public String login(String loginName,String password,Model model,HttpSession session) throws DecoderException
	{
//		if(userService.validate(loginName, password))
//		{
//			return "redirect:/main.do";
//		}
//		else
//		{
//			return "forward:WEB-INF/pages/login.jsp";
//		}
		logger.info("loginName is " + loginName);
		
		if(loginName == null || password == null || 
				StringUtils.isEmpty(loginName) || StringUtils.isEmpty(password))
		{
			model.addAttribute("loginFlag", "用户名或密码为空");
		}
		User nuser = userService.validateByUser(loginName, password);
		
		if(nuser != null)
		{
			logger.info("登录成功");
			session.setAttribute("user", nuser);
			return "redirect:/main";
		}
		else
		{
			model.addAttribute("loginFlag", "用户名或密码错误");
			return "forward:WEB-INF/pages/login.jsp";
		}
	}
	
	@RequestMapping("/main")
	public String main(Model model)
	{
		Integer userId = UserUtils.getCurrentUserId();
		List<Menu> menuList = menuService.getMenuListById(userId);

		//System.out.println("size:" + menuList.size());
		for(Menu menu:menuList)
		{
			if(StringUtils.isEmpty(menu.getIcon()))
			{
				
			}
		}
		model.addAttribute("menuList", menuList);
		model.addAttribute("userName", UserUtils.getCurrentUserName());
		return "main/main";
	}
}
